﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb;
using Webdiyer.WebControls.Mvc;


namespace MinistryStandardPlatformWeb.Controllers
{
    [IsLogin]
    public class UnitController : Controller
    {
        //
        // GET: /Unit/
        private MSPDataContext context = new MSPDataContext();

        [MenuAuthorized("11")]
        public ActionResult Index()
        {
            var rights = from r in context.RightsDetails
                        where r.UserId == CommonFunctions.GetLoginUser().UserId &&
                        //r.HasRight == true &&
                        r.NodeTYPE == true
                        select r;
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                string id = HttpUtility.UrlDecode(Request.QueryString["id"]);
                rights = from r in rights
                        where r.ParentNodeId == id
                        select r;
                
            }

            var units = from r in rights
                    from u in context.InfoUnit
                    where u.UNITID == r.NodeId
                    orderby u.Finsertdate descending
                    select u;

            return PartialView(units.ToPagedList(1,CommonDictionary.PageSize));
        }

        [MenuAuthorized("114")]
        public ActionResult Data(string condition, string unitId, string searchAll, int pageIndex = 1)
        {
            var rights = from r in context.RightsDetails
                         where r.UserId == CommonFunctions.GetLoginUser().UserId &&
                         //r.HasRight == true &&
                         r.NodeTYPE == true
                         select r;
            if (!string.IsNullOrEmpty(unitId) && searchAll != "on")
            {
                rights = from r in rights
                         where r.ParentNodeId == unitId
                         select r;

            }
            if (!string.IsNullOrEmpty(unitId) && searchAll == "on")
            {
                List<string> ids = CommonFunctions.GetAllChildrenUnits(unitId, CommonFunctions.GetLoginUser().UserId);
                ids.Add(unitId);
                rights = from r in rights
                         where ids.Contains(r.ParentNodeId)
                         select r;
            }
            if (!string.IsNullOrEmpty(condition))
            {
                rights = from r in rights
                         where r.NodeName.Contains(condition)
                         select r;

            }
            var units = from r in rights
                        from u in context.InfoUnit
                        where u.UNITID == r.NodeId
                        orderby u.PARTENTUNITID, u.Finsertdate descending
                        select u;
            return PartialView(units.ToPagedList(pageIndex, CommonDictionary.PageSize));
        }

        [MenuAuthorized("111")]
        public ActionResult Create()
        {
            string unitId = HttpUtility.UrlDecode(Request.QueryString["unitId"]);
            string unitName = HttpUtility.UrlDecode(Request.QueryString["unitName"]);
            return View(new InfoUnit()
            {
                PARTENTUNITID = unitId,
                InfoUnit1 = new InfoUnit()
                {
                    UNITID=unitId,
                    UNITNAME=unitName
                }
            });
        }

        [HttpPost]
        [MenuAuthorized("111")]
        public ActionResult Create(InfoUnit unit)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    unit.UNITID = "UNIT" + CommonFunctions.GetDateTimeStrAnd4BitsRandom();
                    unit.Finsertdate = DateTime.Now;
                    unit.InUserID = CommonFunctions.GetLoginUser().UserId;
                    context.InfoUnit.InsertOnSubmit(unit);

                    //添加后要将本单位的权限授予自己
                    RightsDetails right = new RightsDetails();
                    right.UserId = CommonFunctions.GetLoginUser().UserId;
                    right.NodeId = unit.UNITID;
                    right.NodeName = unit.UNITNAME;
                    right.ParentNodeId = unit.PARTENTUNITID;
                    right.NodeTYPE = true;
                    right.HasRight = true;
                    context.RightsDetails.InsertOnSubmit(right);

                
                    context.SubmitChanges();
                    ViewBag.Message = "添加成功";
                }
                catch (System.Exception ex)
                {
                    ViewBag.Message = "添加失败,"+ex.Message;
                }
            }
            else
            {
                ViewBag.Message = "添加失败";
            }
            return View(unit);
        }

        //选择单位的所属单位
        public ActionResult PickParentUnit()
        {
            var units = context.RightsDetails.Where(u => u.UserId == CommonFunctions.GetLoginUser().UserId && u.NodeTYPE == true).Select(u => new { NodeId = u.NodeId, ParentNodeId = u.ParentNodeId, NodeName = u.NodeName });
            List<ZTreeNode> nodes = new List<ZTreeNode>();
            foreach (var unit in units)
            {
                ZTreeNode node = new ZTreeNode();
                node.id = unit.NodeId;
                node.pId = unit.ParentNodeId;
                node.name = unit.NodeName;
                node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                if (unit.ParentNodeId == null)
                {
                    node.open = true;
                }
                else
                {
                    node.open = false;
                }
                nodes.Add(node);
            }
            ViewBag.nodesJson = CommonFunctions.ListToJsonStr<ZTreeNode>(nodes);
            return View();
        }

        public ActionResult HasChildren(string parameters)
        {
            string children = string.Empty;
            if (context.InfoUnit.Any(u => u.PARTENTUNITID == parameters))
            {
                children += "、单位";
            }
            if(context.InfoVehicle.Any(v=>v.ParentUnitId==parameters))
            {
                children+="、车辆";
            }
            if(context.InfoClient.Any(c=>c.ParentUnitId==parameters))
            {
                children+="、客户";
            }
            if (context.InfoTower.Any(t => t.ParentUnitID == parameters))
            {
                children += "、塔楼";
            }
            if (context.InfoContract.Any(c => c.ParentUnitId == parameters))
            {
                children += "、合同";
            }
            if (context.InfoStaff.Any(s => s.ParentUnitId == parameters))
            {
                children += "、人员";
            }
            if (context.LoginUsers.Any(u => u.CustomerID == parameters))
            {
                children += "、用户";
            }

            if (!string.IsNullOrEmpty(children))
            {
                return Json(new { success = "false", message ="该单位下还存在"+ children.Substring(1)+",不能直接删除" });
            }
            else
            {
                return Json(new { success = "true", message = "" });
            }
        }

        [MenuAuthorized("112")]
        public ActionResult Delete(string parameters)
        {
            var unit = context.InfoUnit.SingleOrDefault(u => u.UNITID == parameters);

            //删除权限表中的数据(用触发器实现)
      
            try
            {
                context.InfoUnit.DeleteOnSubmit(unit);
                context.SubmitChanges();
                return Json(new { success ="true", message = "" });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = "false",message=ex.Message });
            }
        }

        [MenuAuthorized("113")]
        public ActionResult Edit(string id)
        {
            var unit = context.InfoUnit.SingleOrDefault(u => u.UNITID == id);
            return View(unit);
        }

        [HttpPost]
        [MenuAuthorized("113")]
        public ActionResult Edit(FormCollection form)
        {
            try
            {
                var unitToUpdate = context.InfoUnit.SingleOrDefault(u => u.UNITID == form["UNITID"]);
                //string oldParent = unitToUpdate.PARTENTUNITID;
                UpdateModel(unitToUpdate, form.ToValueProvider());
                unitToUpdate.Finsertdate = DateTime.Now;
                context.SubmitChanges();
                ViewBag.Message = "修改成功";

                //如果所属单位发生了变化，同时要更新权限表里面的父id(改用触发器来做)
                //if (oldParent != form["ParentUnitId"])
                //{
                //    var rights = context.RightsDetails.Where(r => r.NodeId == unitToUpdate.UNITID).Select(r => r);
                //    foreach (var right in rights)
                //    {
                //        right.ParentNodeId = unitToUpdate.PARTENTUNITID;
                //    }
                //    context.SubmitChanges();
                //}

                return View(unitToUpdate);
            }
            catch (System.Exception ex)
            {
                ViewBag.Message = "修改失败,"+ex.Message;
                return View(new InfoUnit());
            }
        }
    }
}
